<!--
 * @Author: luoyong/471826078@qq.com
 * @Date: 2020-07-02 09:57:17
 * @LastEditors: younghxp
-->
<template>
  <div class="instranceRecord">
    <el-row>
      <el-col :span="24">
        <div class="secondaryTitle secondaryTitleTheme">人员备案记录</div>
        <span class="titleTips"
          >请在每月5日前上传上个月的备案记录，否则将对工伤保险相关业务申报产生影响。</span
        >
      </el-col>
    </el-row>
    <div class="instranceRecordInfo">
      <div class="el-col color333 fontWeight">
        累计备案人数：
        <span class="information">{{ empCount }}人</span>
      </div>
      <div class="el-col color333 fontWeight">
        累计备案人次：
        <span class="information">{{ count }}人</span>
      </div>
      <el-link class="upload" type="primary" @click="downRecords" v-sdc>
        下载人员备案表
        <el-tooltip content="Top center" placement="top" effect="dark">
          <div slot="content">请设置浏览器允许当前页面打开新窗口</div>
          <i class="icon iconfont iconhuabanfuben"></i>
        </el-tooltip>
      </el-link>
    </div>
    <div style="margin-left: 16px">
      <el-table
        :data="tableList"
        empty-text="暂无信息，请及时补充"
        v-loading="loading"
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        highlight-current-row
        style="border: 1px solid #dfe6ec"
        ref="multipleTable"
      >
        <el-table-column
          prop="createTime"
          label="备案时间"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="employeeCount"
          label="备案人数"
          align="center"
        ></el-table-column>
        <el-table-column label="操作" width="300px" align="left">
          <template slot-scope="scope">
            <el-link type="primary" @click="look(scope.row)"
              >人员备案表附件</el-link
            >
            <el-button
              type="primary"
              class="el-links el-links1"
              v-sdc
              @click="downloadRecord(scope.row)"
              >下载人员备案表</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="text-align: right; margin: 10px 0"
        @size-change="handleSizeChange1"
        @current-change="handleCurrentChange1"
        :current-page="pageNo"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <!-- 上传合同附件 -->
    <el-dialog
      title="附件"
      :visible.sync="uploadContract"
      :modal-append-to-body="false"
      :append-to-body="true"
    >
      <!-- <uploadInput></uploadInput> -->
      <uploadAnnex
        @getFileList="getFileList"
        :limitationFactor="limitationFactor"
        @getFile="getFile"
      />

      <el-table
        :data="uploadImg"
        empty-text="暂无附件，请及时上传"
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        highlight-current-row
        style="border: 1px solid #dfe6ec; margin-top: 24px"
      >
        <el-table-column
          prop="createTime"
          label="上传时间"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="name"
          label="文件名称"
          align="center"
        ></el-table-column>
        <el-table-column prop="contentType" label="文件格式" align="center">
          <template slot-scope="scope">
            <span>{{ getFileType(scope.row.name) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              type="primary"
              class="el-links el-links1"
              v-sdc
              @click="downloadRecords(scope.row)"
              >下载附件</el-button
            >
            <el-button
              type="primary"
              class="el-links el-links1"
              style="margin-left: 0"
              v-sdc
              @click="deleteRecords(scope.row)"
              >删除附件</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>
<script>
import common from '../../kits/common'

export default {
  name: 'instranceRecord',
  data() {
    return {
      requestUrl: '',
      tableList: [],
      pageNo: 1,
      pageSize: 5,
      total: 0,
      isShow: false, //列表加载
      loading: false,
      empCount: 0,
      count: 0,
      newEmpCount: 0,
      recordId: '',
      uploadContract: false,
      uploadImg: [],
      saveImgArr: [],
      srcList: [],
      oldSrcList: [],
      limitationFactor: {
        uploadAnnexUrl: 'api-f/files/upload', //自定义上传文件接口地址
        upLoadFileLength: '', //自定义上传文件最大数量设置
        fileSize: 5, //自定义上传文件最大设置
        messagetip: '仅支持上传jpg、png、jpeg、PDF、word、xls、xlsx格式文件', //自定义报错提示语
        formatType: 'typeFour', //自定义上传格式校验类型
        fileId: 'salaryExcel', //自定义id解决一个页面包含多个上传附件
        uploadFormId: 'salaryExcelForm', //自定义id解决一个页面包含多个上传附件
        methodTip: '', //自定义上传文件提示
        uploadBtnType: 'typeTwo', //自定义上传按钮类型
        UploadType: 'typeTwo', //自定义上传附件类型
      },
    }
  },
  props: {
    projectId: {
      type: String,
      required: true,
    },
  },
  watch: {
    projectId(val, val1) {
      this.getRecordInfo(val)
      this.getTableList(val, this.pageNo, this.pageSize)
    },
  },
  methods: {
    /**
     * @name: 截取文件后缀
     * @param {type}
     * @Author: luoyong
     */

    getFileType(file) {
      const fileName = file.lastIndexOf('.') // 取到文件名开始到最后一个点的长度
      const fileNameLen = file.length // 取到文件名长度
      const fileType = file.substring(fileName + 1, fileNameLen) // 截
      return '.' + fileType
    },
    /**
     * @name: 获取备案记录信息
     * @param {type}
     * @Author: luoyong
     */
    getRecordInfo(projectId) {
      this.axios({
        method: 'post',
        url: '/api-e/cs/emprecord/expand/statistics',
        data: {
          projectId,
        },
      })
        .then((response) => {
          if (!response.data.false) {
            this.empCount = response.data.result.empCount
            this.count = response.data.result.count
            this.newEmpCount = response.data.result.newEmpCount
          } else {
            this.$message({
              message: resp.data.errorMsg,
              type: 'error',
            })
          }
        })
        .catch((error) => {})
    },
    // 获取列表数据
    getTableList(projectId, pageNo, pageSize) {
      this.isShow = true
      this.loading = true
      this.axios({
        method: 'post',
        url: '/api-e/cs/emprecord/expand/list',
        data: {
          projectId,
          pageNo,
          pageSize,
        },
      })
        .then((response) => {
          if (!response.data.false) {
            this.tableList = response.data.result.results
            if (response.data.result.totalCount > 0) {
              this.total = response.data.result.totalCount
            }
          } else {
            this.$message({
              message: resp.data.errorMsg,
              type: 'error',
            })
          }
          this.isShow = false
          this.loading = false
        })
        .catch((error) => {})
    },
    handleSizeChange1(val) {
      this.pageSize = val
      this.getTableList(this.projectId, this.pageNo, val)
    },
    handleCurrentChange1(val) {
      this.pageNo = val
      this.getTableList(this.projectId, val, this.pageSize)
    },
    downRecords() {
      let that = this
      this.axios({
        method: 'post',
        url: '/api-e/cs/emprecord/expand/statistics',
        data: {
          projectId: this.projectId,
        },
      })
        .then((response) => {
          if (!response.data.false) {
            that.empCount = response.data.result.empCount
            that.count = response.data.result.count
            that.newEmpCount = response.data.result.newEmpCount
            if (that.newEmpCount == 0) {
              that.$message({
                type: 'error',
                message: '暂时没有新增备案人员记录',
              })
            } else {
              that
                .$confirm(
                  that.tableList.length == 0
                    ? `本次为首次下载人员备案表，本项目至今累计进场实名制人员${that.newEmpCount}人,
             是否下载?下载后请盖章上传至系统附件中，
             系统将推送至所在地工伤保险经办机构`
                    : `对比上次备案记录，本次新增进场实名制人员${that.newEmpCount}人,
             是否下载新增进场实名制人员备案表?下载后请盖章上传至系统附件中，
             系统将推送至所在地工伤保险经办机构`,
                  '提醒',
                  {
                    confirmButtonText: '下载',
                    cancelButtonText: '取消',
                    type: 'warning',
                  }
                )
                .then(() => {
                  let url =
                    common.commonApi +
                    'api-e/cs/emprecord/expand/newrecord?projectId=' +
                    that.projectId +
                    '&access_token=' +
                    localStorage.getItem('access_token')
                  var net = window.open(url)
                  net.addEventListener('beforeunload', (e) => {
                    //   setTimeout(()=>{
                    //         that.getTableList(
                    //         that.projectId,
                    //         that.pageNo,
                    //         that.pageSize
                    //         );
                    //   },3000)
                    this.$nextTick(() => {
                      that.getTableList(
                        that.projectId,
                        that.pageNo,
                        that.pageSize
                      )
                      that.getRecordInfo(that.projectId)
                    })
                  })
                })
                .catch(() => {
                  that.$message({
                    type: 'info',
                    message: '已取消下载人员备案表',
                  })
                })
            }
          } else {
            that.$message({
              message: resp.data.errorMsg,
              type: 'error',
            })
          }
        })
        .catch((error) => {})
    },
    /**
     * @name: 修改-打开上传附件弹窗
     * @param {string} id 参保记录id
     * @Author: luoyong
     */
    look(item) {
      this.uploadContract = true
      this.recordId = item.id
      this.uploadImg = []
      //   this.saveImgArr = [];
      //   this.srcList = [];
      //   this.oldSrcList = [];
      this.getUploadFiles(item.id)
    },
    /**
     * @name: 获取已上传的附件
     * @param {string} recordId 备案记录id
     * @Author: luoyong
     */
    getUploadFiles(recordId) {
      this.axios({
        method: 'post',
        url: '/api-e/cs/emprecord/expand/recordfiles',
        data: { recordId },
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.uploadImg = response.data.result ? response.data.result : []
            // for (var i = 0; i < this.uploadImg.length; i++) {
            //   this.saveImgArr.push({
            //     originalName: this.uploadImg[i].originalName,
            //     relativePath: this.uploadImg[i].relativePath,
            //     fileSize: this.uploadImg[i].fileSize,
            //     fileType: this.uploadImg[i].fileType
            //   });
            //   this.srcList.push(this.uploadImg[i].absolutePath);
            //   this.oldSrcList.push(this.uploadImg[i].absolutePath);
            // }
          } else {
            this.$message({
              type: 'error',
              message: '数据获取失败',
            })
          }
        })
        .catch((error) => {})
    },
    cancelUpload() {
      this.uploadContract = false
    },
    //保存附件
    saveUpload(uploadImg) {
      // this.canLogin = true;
      var data = {
        fileList: JSON.stringify(uploadImg),
        recordId: this.recordId,
      }
      this.axios({
        method: 'post',
        url: '/api-e/cs/emprecord/expand/addfile',
        data: data,
      })
        .then((response) => {
          this.canLogin = false
          if (!response.data.hasError) {
            this.$message({
              type: 'success',
              message: '附件上传成功',
            })
            this.getUploadFiles(this.recordId)
            // this.getTableList(val, this.pageNo, this.pageSize);
          } else {
            this.$message({
              type: 'error',
              message: '保存失败',
            })
          }
        })
        .catch((error) => {
          this.canLogin = false
        })
    },
    /**
     * @name: 修改-工伤保险-参保记录
     * @param {string} id 参保记录id
     * @Author: luoyong
     */
    downloadRecord(item) {
      window.location.href =
        common.commonApi +
        '/api-e/cs/emprecord/expand/downloadrecord?recordId=' +
        item.id +
        '&access_token=' +
        localStorage.getItem('access_token')
    },
    downloadRecords(item) {
      window.location.href = item.url
    },
    deleteRecords(item) {
      let that = this
      this.$confirm('此操作将永久删除该附件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.axios({
            method: 'post',
            url: '/api-e/cs/emprecord/expand/delfile',
            data: {
              fileIds: JSON.stringify([item.id]),
            },
          })
            .then((response) => {
              if (!response.data.hasError) {
                that.$message({
                  message: '删除成功',
                  type: 'success',
                })

                that.getUploadFiles(that.recordId)
              } else {
                this.$message({
                  message: resp.data.errorMsg,
                  type: 'error',
                })
              }
            })
            .catch((error) => {})
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    getFile(val) {
      this.saveUpload([val])
    },
    getFileList(val) {},
  },
  mounted() {
    if (this.$route.query.projectId) {
      this.getRecordInfo(this.$route.query.projectId)
      this.getTableList(this.$route.query.projectId, this.pageNo, this.pageSize)
    }
  },
}
</script>
<style lang="less" scoped>
.instranceRecordInfo {
  color: #666;
}
.instranceRecord {
  background-color: #fff;
  padding: 24px 24px 1px;
  &Info {
    position: relative;
    margin-top: 5px;
    margin-left: 16px;
    font-size: 14px;
    .el-col {
      height: 36px;
      line-height: 36px;
      display: inline-block;
      margin-right: 45px;
    }
    .upload {
      position: absolute;
      top: 8px;
      right: 0;
    }
  }
  .el-table {
    margin-top: 5px;
  }
}

.titleTips {
  display: block;
  font-size: 14px;
  line-height: 14px;
  height: 14px;
  margin-left: 16px;
  margin-top: 10px;
  color: #a3a3a3;
}
.uploadBox {
  position: relative;
  .upLoadDom {
    position: absolute;
    top: 0;
    left: 0;
    opacity: 0;
    input {
      // font-size: 0;
      width: 136px;
      height: 36px;
      cursor: pointer;
    }
  }
}
.imgStyle {
  margin-top: 20px;
  li {
    position: relative;
    margin-right: 20px;
    margin-top: 10px;
    i {
      position: absolute;
      right: -6px;
      top: -10px;
      font-size: 20px;
    }
  }
}
.el-links {
  background-color: transparent;
  border: none;
  outline: none;
  color: #48a6ff;

  &:hover {
    text-decoration: underline #48a6ff !important;
    background-color: transparent !important;
    background: transparent !important;
    color: #48a6ff !important;
  }
}
.el-links1:hover {
  background-color: transparent !important;
  background: transparent !important;
  color: #48a6ff !important;
}
.information {
  font-size: 14px;
  color: #666;
  line-height: 36px;
  font-weight: 400;
}
</style>
